package com.java.base.io.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class BIOSocket {


    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocket serverSocket = new ServerSocket(0xaaaa);
        new Thread(() -> {
            try {
                testOutput();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
        Socket socket = serverSocket.accept();
        int i;
        byte[] bs = new byte[8192];
        String last = null;
        while (!socket.isClosed()) {
//            Thread.sleep(10);
            i = socket.getInputStream().read(bs);
            if (i < 0) {
                break;
            }
            String s = new String(bs, 0, i, StandardCharsets.US_ASCII);
            if (!s.equals(last)) {
                System.out.println("接收方读：" + s.charAt(0));
                last = s;
            }
        }

        socket.close();
    }

    public static void testOutput() throws IOException {
        Socket socket = new Socket("127.0.0.1", 0xaaaa);
        byte[] bytes = new byte[1024];

        for (int i = 0; i < 100000; i++) {
            int x = i % 26 + 65;
            for (int j = 0; j < 1024; j++) {
                bytes[j] = (byte) x;
            }
            socket.getOutputStream().write(bytes);
            System.err.println("发送方写：" + i);
        }
        socket.close();

    }

    public static void client() throws IOException {
        Socket socket = new Socket("127.0.0.1", 0xaaaa);
        new Thread(() -> {
            byte[] bytes = new byte[1024];
            int i;
            String s;
            while (!socket.isClosed()) {
                try {
                    i = socket.getInputStream().read(bytes);
                    s = new String(bytes, 0, i);
                    System.out.println("有人说：" + s);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        Scanner scanner = new Scanner(System.in);
        System.err.println("输入：");
        while (!socket.isClosed()) {
            String s = scanner.nextLine();
            if (s.equals("stop")) {
                System.out.println("结束程序");
                socket.close();
                break;
            }
            socket.getOutputStream().write(s.getBytes(StandardCharsets.UTF_8));
        }
    }


}
